<?php
/**
 * The wire's JavaScript
 */

$site_url = elgg_get_site_url();

?>

elgg.provide('elgg.rsactivity');

elgg.rsactivity.init = function() {
	$("#rsactivity-textarea").live('keydown', function() {
		elgg.rsactivity.textCounter(this, $("#rsactivity-characters-remaining span"), 140);
	});
	$("#rsactivity-textarea").live('keyup', function() {
		elgg.rsactivity.textCounter(this, $("#rsactivity-characters-remaining span"), 140);
	});

	$(".rsactivity-previous").live('click', elgg.rsactivity.viewPrevious);
	
};

/**
 * Update the number of characters left with every keystroke
 *
 * @param {Object}  textarea
 * @param {Object}  status
 * @param {integer} limit
 * @return void
 */
elgg.rsactivity.textCounter = function(textarea, status, limit) {

	var remaining_chars = limit - $(textarea).val().length;
	status.html(remaining_chars);

	if (remaining_chars < 0) {
		status.parent().css("color", "#D40D12");
		$("#rsactivity-submit-button").attr('disabled', 'disabled');
		$("#rsactivity-submit-button").addClass('elgg-state-disabled');
	} else {
		status.parent().css("color", "");
		$("#rsactivity-submit-button").removeAttr('disabled', 'disabled');
		$("#rsactivity-submit-button").removeClass('elgg-state-disabled');
	}
};

/**
 * Display the previous wire post
 *
 * Makes Ajax call to load the html and handles changing the previous link
 *
 * @param {Object} event
 * @return void
 */
elgg.rsactivity.viewPrevious = function(event) {
	var $link = $(this);
	var postGuid = $link.attr("href").split("/").pop();
	var $previousDiv = $("#rsactivity-previous-" + postGuid);

	if ($link.html() == "<?php echo elgg_echo('rsactivity:hide'); ?>") {
		$link.html("<?php echo elgg_echo('rsactivity:previous'); ?>");
		$link.attr("title", "<?php echo elgg_echo('rsactivity:previous:help'); ?>");
		$previousDiv.slideUp(400);
	} else {
		$link.html("<?php echo elgg_echo('rsactivity:hide'); ?>");
		$link.attr("title", "<?php echo elgg_echo('rsactivity:hide:help'); ?>");
		
		$.ajax({type: "GET",
			url: "<?php echo $site_url . "ajax/view/rsactivity/previous"; ?>",
			dataType: "html",
			cache: false,
			data: {guid: postGuid},
			success: function(htmlData) {
				if (htmlData.length > 0) {
					$previousDiv.html(htmlData);
					$previousDiv.slideDown(600);
				}
			}
		});

	}

	event.preventDefault();
};


elgg.register_hook_handler('init', 'system', elgg.rsactivity.init);
